package com.cheetah.start.common.config;

import com.alibaba.fastjson.JSONObject;
import com.cheetah.start.common.base.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.validation.ValidatorManager;

/**
 * 参数校验配置
 *
 * @author xjh
 * @date 2022/06/18
 */
@Slf4j
@Configuration
public class ValidConfig {


    @Bean
    public void validInit() {
        ValidatorManager.setFailureHandler((ctx, ano, rst, message) -> {
            ctx.setHandled(true);
            ctx.setRendered(true);

            if (Utils.isEmpty(message)) {
                message = "@" +
                        ano.annotationType().getSimpleName() +
                        " verification failed";
            }

            Result<Object> failure = Result.failure(message);
            String res = JSONObject.toJSONString(failure);
            log.warn(res);
            ctx.output(res);
            return false;
        });
    }
}
